import router from '@/router/index.ts';
import {useUserStore} from "@/store/user";
import {useMenuStore} from "@/store/menu";

//定义白名单
const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const menuStore = useMenuStore()
    const token = userStore.getToken
    if (token) {//如果存在token
        if (to.path == '/login' || to.path == '/') {//如果是从登陆页来的请求或者请求的是首页跳转首页
            next({path: '/'})
        } else {//请求的是除了主页外的其他页面需要从store里查看是否存在权限
            const hasRoles = userStore.getCodeList.length > 0
            if (hasRoles) {//存在权限放行
                next()
            } else {//否则从服务器查询
                try {
                    //获取用户信息
                    await userStore.getInfo()
                    //获取菜单数据
                    await menuStore.getMenuList(router, userStore.getUserId)
                    //等待路由完全挂载
                    next({...to, replace: true})
                } catch (error) {
                    //清空数据
                    sessionStorage.clear()
                    //跳转登陆
                    next({path: '/login'})
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) != -1) {//请求在白名单放行
            next()
        } else {
            next({path: '/login'})//不在白名单跳转登陆页
        }
    }
})
